<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="90px"
      style="margin-left: -20px"
    >
      <el-form-item label="传感器类型">
        <!--  clearable -->
        <el-select
          v-model="queryParams.type"
          placeholder="传感器类型"
          size="small"
          @clear="cleartype"
          @change="changetype"
          :popper-append-to-body="false"
          style="width: 130px; margin-right: 5px"
        >
          <el-option
            v-for="dicts in types"
            :key="dicts.value"
            :label="dicts.lable"
            :value="dicts.value"
          />
        </el-select>
        <el-select
          v-model="queryParams.ssTransducerType"
          placeholder="请选择传感器类型"
          size="small"
          @clear="clearsducerCode"
          @change="changeTypes"
          :popper-append-to-body="false"
          :disabled="isTypesducerCode"
        >
          <el-option
            v-for="dicts in typeList"
            :key="dicts.ss_transducer_type"
            :label="dicts.ss_transducer_name"
            :value="dicts.ss_transducer_type"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="time" style="margin-left: -30px">
        <el-date-picker
          v-model="queryParams.time"
          type="datetimerange"
          range-separator="至"
          @change="handleTime"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="传感器名称" style="margin-left: 13px">
        <!-- :disabled="!typeId" -->
        <el-select
          v-model="queryParams.sensorName"
          placeholder="请选择传感器名称"
          clearable
          multiple
          collapse-tags
          size="small"
          @change="changeSensor"
          :popper-append-to-body="false"
          style="width: 420px"
        >
          <el-option
            v-for="(dicts, index) in sensorList"
            :key="index"
            :label="dicts.ss_transducer_point"
            :value="dicts.ss_transducer_code"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 20px">
        <el-button type="primary" size="mini" @click="finish"
          >生成曲线</el-button
        >
        <el-button type="primary" size="mini" @click="finishtable"
          >生成表格</el-button
        >
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetForm('queryForm')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div>
      <div>
        <el-button type="primary" plain @click="btnMin(1)">1小时</el-button>
        <el-button type="primary" plain @click="btnMin(3)">3小时</el-button>
        <el-button type="primary" plain @click="btnMin(8)">8小时</el-button>
      </div>
      <!-- <echart :chartData="echartData.yield"></echart> -->
      <div id="line_chart" v-if="ischart"></div>
    </div>
    <div class="line_table" v-if="istable">
      <el-table v-loading="loading" :data="tableList" height="350">
        <el-table-column label="煤矿名称">
          <template slot-scope="scope">
            <span v-if="MineName != '' && MineName != 'null'">{{
              MineName
            }}</span>
            <span v-if="MineName == '' || MineName == 'null'">{{
              scope.row.cs_mine_shortname
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cs_mine_code" label="煤矿编号">
        </el-table-column>
        <el-table-column
          prop="ss_transducer_point"
          label="传感器监测地点"
          width="250"
        >
        </el-table-column>
        <el-table-column prop="ss_transducer_type_name" label="传感器类型">
        </el-table-column>
        <!-- <el-table-column prop="in_out_type" label="类型">
          <template slot-scope="scope">
            <span>{{
              scope.row.in_out_type == '1'
                ? '模拟量'
                : scope.row.in_out_type == '2'
                ? '开关量'
                : ''
            }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="ss_transducer_state_name" label="传感器状态">
        </el-table-column>
        <!-- <el-table-column prop="area_code" label="所在区域"> </el-table-column> -->
        <el-table-column
          prop="ss_transducer_value"
          label="监测值"
          v-if="this.queryParams.type == 1"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.in_out_type == "1"
                ? scope.row.ss_transducer_value + "(" + scope.row.company + ")"
                : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ss_transducer_value_name"
          label="监测值"
          v-if="this.queryParams.type == 2"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.in_out_type == "2"
                ? scope.row.ss_transducer_value_name
                : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cs_data_time" label="数据时间" width="230">
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getListdata"
      />
    </div>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  addInfo,
  updateInfo,
  updateInfo1
} from "@/api/security/safepolice";
import * as echarts from "echarts";
import Vue from "vue";
Vue.prototype.$echarts = echarts;
// import Echart from '@/components/Echart'
export default {
  components: {},
  data() {
    return {
      ischart: false,
      istable: false,
      queryParams: {
        csMineCode: "",
        inOutType: "",
        ssTransducerCode: "",
        ssTransducerPoint: "",
        ssTransducerTypeName: "",
        ssTransducerCodeList: "",
        time: [],
        endDate: "",
        startDate: "",
        endTime: "",
        startTime: "",
        sensorName: []
      },
      query: {
        pageNum: 1,
        pageSize: 20
      },
      querys: {
        pageNum: 1,
        pageSize: 10
      },
      echartData: {
        yield: {
          xData: [],
          series: [],
          yAxis: {}
        }
      },
      csMineName: "",
      names: "",
      total: 0,
      tableList: [0, 1, 5, 15, 12],
      coalmineList: ["5545", ""],
      MineCode: "",
      MineName: "",
      info: {},
      lineList: [],
      typeList: [],
      types: [
        {
          lable: "模拟量",
          value: "1"
        },
        {
          lable: "开关量",
          value: "2"
        }
      ],
      typevalue: "",
      isTypesducerCode: true,
      sensorList: [],
      typeId: "",
      starttime: "",
      endtime: "",
      total: 0,
      timeOptionRange: '',
      pickerMinDate: null,
      pickerMaxDate: null,
      day7: 7 * 24 * 3600 * 1000,
      pickerOptions: {
        onPick: ({ minDate }) => {
          if (minDate && this.pickerMinDate) {
            this.pickerMinDate = null;
          } else if (minDate) {
            this.pickerMinDate = minDate.getTime();
          }
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            return time.getTime() > this.pickerMinDate + this.day7 || time.getTime() < this.pickerMinDate - this.day7;
          }
          return false;
        }
      }
    };
  },
  mounted() {
    // if (location.href.indexOf('#reloaded') == -1) {
    //   location.href = location.href + '#reloaded'
    //   location.reload()
    // }
    this.starttime = this.getYMDHMS(
      new Date(this.getTimeNow()).getTime() - 86400000
    );
    this.queryParams.time.push(this.starttime, this.getTimeNow());
    if (
      this.queryParams.inOutType &&
      this.queryParams.time.length == 2 &&
      this.queryParams.sensorName.length > 0
    ) {
      this.line_chart("line_chart");
    }
  },
  created () {
    this.getSensor();
  },
  methods: {
    // 时间格式化
    dateconvert(time) {
      time = new Date(time);
      var datetimeFormat = "yyyy-MM-dd hh:mm:ss";
      var o = {
        "M+": time.getMonth() + 1, // 月份
        "d+": time.getDate(), // 日
        "h+": time.getHours(), // 小时
        "m+": time.getMinutes(), // 分
        "s+": time.getSeconds(), // 秒
        "q+": Math.floor((time.getMonth() + 3) / 3), // 季度
        S: time.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(datetimeFormat)) {
        datetimeFormat = datetimeFormat.replace(
          RegExp.$1,
          (time.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(datetimeFormat)) {
          datetimeFormat = datetimeFormat.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return datetimeFormat;
    },
    line_chart(id) {
      this.chart = echarts.init(document.getElementById(id));
      this.chart.clear();
      const option = {
        title: {
          text: "传感器变化曲线图",
          left: "center"
        },
        tooltip: {
          // 鼠标滑过提示框样式
          trigger: "item",
          padding: 10,
          backgroundColor: "#7bdeff70",
          formatter: function(a) {
            return a.data[0] + "</br>" + a.seriesName + "--" + a.data[1] + "";
          }
        },
        legend: {
          // 图例样式
          orient: "vertical",
          y: "top",
          top: "5%",
          right: "0%",
          textStyle: {
            color: "#666", // 图例文字颜色
            fontWeight: "bold"
          }
        },
        grid: {
          // 折线位置
          top: "8%",
          right: "20%"
        },
        xAxis: {
          // x轴样式
          type: "time",
          name: "时间",
          nameTextStyle: { fontSize: 15, color: "#666" },
          // boundaryGap: false,
          boundaryGap: [0, 0.05],
          axisLine: {
            lineStyle: {
              color: "#666"
            }
          },
          axisTick: {
            show: true
          },
          splitLine: {
            show: false,
            //  改变轴线颜色
            lineStyle: {
              color: "#666"
            }
          }
        },
        yAxis: {
          // y轴样式
          type: "value",
          name: "传感器值",
          nameTextStyle: { fontSize: 15, color: "#666" },
          axisLabel: {
            show: true
          },
          axisLine: {
            lineStyle: {
              color: "#666"
            }
          },
          axisTick: {
            // show: true,
            alignWithLabel: true
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#666"
            }
          }
        },

        calculable: true,
        color: [
          "red",
          "#34affd",
          "#ff5555",
          "#ffde00",
          "#5af4ce",
          "#d050ff",
          "#CD5C5C",
          "#4DCD53",
          "#F1AB27",
          "#B96CD3"
        ], // 折线颜色
        series: [],
        animation: false
      };

      // var datas = []
      var arr = [];
      var temp = null;
      // this.lineList = [
      //   {
      //     time: [
      //       '2022-01-20 09:08:54',
      //       '2022-01-20 10:10:54',
      //       '2022-01-20 11:12:54',
      //       '2022-01-21 05:05:02',
      //       '2022-01-21 10:12:54'
      //     ],
      //     value: [5, 10, 15, 7, 9]
      //   },
      //   {
      //     time: [
      //       '2022-01-20 09:09:54',
      //       '2022-01-20 13:11:02',
      //       '2022-01-21 15:12:54',
      //       '2022-01-21 17:15:54'
      //     ],
      //     value: [2, 4, 6, 8]
      //   }
      // ]
      this.lineList.forEach(item => {
        this.$set(item, "data", []);
        arr = [];
        item.data.push([item.time, item.value]);
        for (var i = 0; i < item.data[0][0].length; i++) {
          arr.push([item.data[0][0][i], item.data[0][1][i]]);
        }
        temp = {
          name: item.name,
          type: "line",
          data: arr,
          step: "start"
        };
        option.series.push(temp);
        // console.log(353, arr)
        // datas.push(arr)
      });

      // console.log(520, datas)

      console.log(392, option.series);
      this.chart.setOption(option);
    },
    cleartype() {
      this.queryParams.inOutType = "";
      this.isTypesducerCode = true;
      this.getList();
    },
    clearsducerCode() {
      this.getList();
    },
    changetype(e) {
      this.typevalue = e;
      this.queryParams.ssTransducerType=''
      this.queryParams.sensorName=''
      this.queryParams.inOutType = "";
      this.isTypesducerCode = false;
      this.getType();
      this.getSensor();
    },
    getType() {
      var typevalue = {
        type: this.typevalue
      };
      listInfo(typevalue).then(response => {
        console.log(450, response);
        if (response.code === 200) {
          this.typeList = response.data;
        }
      });
    },
    finish() {
      this.ischart = true;
     this.istable = false;
      if (
       // this.queryParams.type &&
        this.queryParams.time.length == 2 &&
        this.queryParams.sensorName.length > 0
      ) {
        this.getList();
      }
       else {
        this.$message("请选择条件信息");
       }
    },
    finishtable() {
      this.ischart = false;
      if (
       // this.queryParams.type &&
        this.queryParams.time.length == 2 &&
        this.queryParams.sensorName.length > 0
      ) {
        this.istable = true;
        this.getListdata();
      } else {
        this.$message("请选择条件信息");
      }
    },
    getSensor() {
      console.log(483, this.queryParams);
      getInfo(this.queryParams).then(response => {
        console.log(492, response);
        if (response.code === 200) {
          this.sensorList = response.data;
        }
      });
    },
    changeMine() {
      this.queryParams.inOutType = "";
    },
    changeTypes(e) {
      this.typeId = e;
      this.queryParams.sensorName = [];
      this.queryParams.endTime = this.queryParams.time[1];
      this.queryParams.startTime = this.queryParams.time[0];
      this.getSensor();
      this.lineList = [];
    },
    changeSensor(e) {
      this.queryParams.ssTransducerCodeList = e.join(",");
    },
    btnMin(type) {
      this.queryParams.time = [];
      if (type == 1) {
        this.starttime = this.getYMDHMS(
          new Date(this.getTimeNow()).getTime() - 3600000
        );
      } else if (type == 3) {
        this.starttime = this.getYMDHMS(
          new Date(this.getTimeNow()).getTime() - 10800000
        );
      } else if (type == 8) {
        this.starttime = this.getYMDHMS(
          new Date(this.getTimeNow()).getTime() - 28800000
        );
      }
      this.queryParams.time.push(this.starttime, this.getTimeNow());
      if (
        this.queryParams.inOutType &&
        this.queryParams.time.length == 2 &&
        this.queryParams.sensorName.length > 0
      ) {
        if (this.ischart) {
          this.getList();
          this.line_chart("line_chart");
        } else if (this.istable) {
          this.getListdata();
        }
      }
    },
    getListdata() {
      this.tableList = [];
      this.loading = true;
      this.queryParams.endDate = this.queryParams.time[1];
      this.queryParams.startDate = this.queryParams.time[0];
      // '/safe/ssHistoryTable?csMineCode=' +
      //       this.queryParams.csMineCode +
      //       '&endDate=' +
      //       this.queryParams.time[1] +
      //       '&startDate=' +
      //       this.queryParams.time[0] +
      //       '&ssTransducerCodeList=' +
      //       this.queryParams.sensorName +
      //       '&pageNum=' +
      //       this.querys.pageNum +
      //       '&pageSize=' +
      //       this.querys.pageSize
      updateInfo1(this.queryParams)
        .then(res => {
          console.log(551, res);
          this.tableList = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getList() {
      this.lineList = [];
      this.queryParams.endDate = this.queryParams.time[1];
      this.queryParams.startDate = this.queryParams.time[0];
      updateInfo(this.queryParams).then(res => {
        this.lineList = res.data;
        if (this.lineList.length > 0) {
          this.line_chart("line_chart");
        } else {
          this.$message("暂无相关数据");
        }
      });
    },
    handleTime(e) {
      this.starttime = this.formatDate(e[0]);
      this.endtime = this.formatDate(e[1]);
      var time =
        new Date(this.formatDate(e[1])).getTime() -
        new Date(this.formatDate(e[0])).getTime();
      // if (time > 86400000) {
      //   this.starttime = this.getYMDHMS(
      //     new Date(this.formatDate(e[1])).getTime() - 86400000
      //   )
      // }
      this.queryParams.time = [this.starttime, this.endtime];
      this.queryParams.endTime = this.queryParams.time[1];
      this.queryParams.startTime = this.queryParams.time[0];
      this.getSensor();
    },
    getYMDHMS(timestamp) {
      const time = new Date(timestamp);
      const year = time.getFullYear();
      let month = time.getMonth() + 1;
      let date = time.getDate();
      let hours = time.getHours();
      let minute = time.getMinutes();
      let second = time.getSeconds();

      if (month < 10) {
        month = "0" + month;
      }
      if (date < 10) {
        date = "0" + date;
      }
      if (hours < 10) {
        hours = "0" + hours;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      return (
        year +
        "-" +
        month +
        "-" +
        date +
        " " +
        hours +
        ":" +
        minute +
        ":" +
        second
      );
    },
    formatDate(date) {
      // 设置时间转换格式
      var y = date.getFullYear(); // 获取年
      var m = date.getMonth() + 1; // 获取月
      m = m < 10 ? "0" + m : m; // 判断月是否大于10
      var d = date.getDate(); // 获取日
      d = d < 10 ? "0" + d : d; // 判断日期是否大10
      let h = date.getHours(); // 11
      h = h < 10 ? "0" + h : h; // 判断日期是否大10
      let mm = date.getMinutes(); // 14
      mm = mm < 10 ? "0" + mm : mm; // 判断日期是否大10
      let s = date.getSeconds(); // 44
      s = s < 10 ? "0" + s : s; // 判断日期是否大10
      return y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + s; // 返回时间格式
    },
    getTimeNow() {
      const date = new Date(); //   Wed Aug 26 2020 11:14:44 GMT+0800 (中国标准时间)
      const year = date.getFullYear(); // 2020
      let month = date.getMonth() + 1; // 8
      let day = date.getDate(); // 26
      let h = date.getHours(); // 11
      let m = date.getMinutes(); // 14
      let s = date.getSeconds(); // 44
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      if (h < 10) {
        h = "0" + h;
      }
      if (m < 10) {
        m = "0" + m;
      }
      if (s < 10) {
        s = "0" + s;
      }
      return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s; // 返回时间格式
    }
  }
};
</script>

<style lang="scss" scoped>
#line_chart {
  width: 84vw;
  height: 60vh;
  margin-top: 3vh;
  margin-left: 0vh;
}
.line_table {
  width: 100%;
  height: 60vh;
  margin-top: 3vh;
  margin-left: 0vh;
}
</style>
